package cc.javaee.bbs.dao.activity;

import cc.javaee.bbs.exception.ResultException;
import cc.javaee.bbs.model.activity.BankuaiCustomer;
import cc.javaee.bbs.request.KoboroRequest;
import cc.javaee.bbs.vo.ResultVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xdw
 */
@Service
public class BankuaiCustomerService {

    @Resource
    private BankuaiCustomerDao bankuaiCustomerDao;

    public Integer insert(BankuaiCustomer bankuaiCustomer) {
        return bankuaiCustomerDao.insert(bankuaiCustomer);
    }

    public BankuaiCustomer findByArchivalNumber(String archivalNumber) {
        BankuaiCustomer customer = new BankuaiCustomer();
        customer.setArchivalNumber(archivalNumber);
        List<BankuaiCustomer> bankuaiCustomers = bankuaiCustomerDao.find(customer);
        if (CollectionUtils.isNotEmpty(bankuaiCustomers)) {
            return bankuaiCustomers.get(0);
        } else {
            return null;
        }
    }

    public void joinBankuai(String archivalNumber, Integer id) throws ResultException {
        //添加报名用户
        Map customer = KoboroRequest.getCustomer(archivalNumber);
        if (MapUtils.isEmpty(customer)) {
            throw new ResultException(-1, "用户不存在");
        }
        BankuaiCustomer bankuaiCustomer = getBankuaiCustomer(archivalNumber, id);
        if (bankuaiCustomer == null) {
            bankuaiCustomer = new BankuaiCustomer();
            bankuaiCustomer.setCreateTime(new Date());
            bankuaiCustomer.setBankuaiId(id);
            bankuaiCustomer.setArchivalNumber(archivalNumber);
            bankuaiCustomer.setImgPath((String) customer.get("imgFullPath"));
            bankuaiCustomer.setCustName((String) customer.get("name"));
            bankuaiCustomer.setCustId((Integer) customer.get("id"));
        } else {
            throw new ResultException(-1, "用户已加入圈子");
        }
        bankuaiCustomerDao.insert(bankuaiCustomer);
    }

    public BankuaiCustomer getBankuaiCustomer(String archivalNumber, Integer id) {
        BankuaiCustomer bankuaiCustomer = new BankuaiCustomer();
        bankuaiCustomer.setBankuaiId(id);
        bankuaiCustomer.setArchivalNumber(archivalNumber);

        List<BankuaiCustomer> bankuaiCustomers = bankuaiCustomerDao.find(bankuaiCustomer);
        if (CollectionUtils.isNotEmpty(bankuaiCustomers)) {
            return bankuaiCustomers.get(0);
        }
        return null;
    }

}
